package com.sywb.chuangyebao.view.fragment;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.sywb.chuangyebao.Constants;
import com.sywb.chuangyebao.R;
import com.sywb.chuangyebao.bean.DistrictInfo;
import com.sywb.chuangyebao.utils.HttpCallback;
import com.sywb.chuangyebao.utils.HttpUtils;
import com.sywb.chuangyebao.utils.RegexUtils;
import com.sywb.chuangyebao.view.dialog.WheelViewDialog;

import org.bining.footstone.db.DbManager;
import org.bining.footstone.utils.ToastUtils;

/**
 * 创业万里行-报名
 */
public class EnrollFragment extends BaseStatisticsFragment {

    TextView etIndustry;
    TextView etCity;
    EditText etIntro;
    EditText etContacts;
    EditText etMobile;
    Button btnComplete;

    public WebView wvContent;

    private int categoryId;
    private String area;

    private String oldIndustry, oldCity, oldIntro, oldContacts, oldMobile;

    /**
     * Fragment 实例
     */
    public static EnrollFragment newInstance(Object... pramars) {
        EnrollFragment fragment = new EnrollFragment();
        fragment.setArguments(getBundle(pramars));
        return fragment;
    }

    @Override
    public int getLayoutId(Bundle bundle) {
        return R.layout.activity_enroll;
    }

    @Override
    public void initView(View view, Bundle bundle) {
        super.initView(view, bundle);
        etIndustry = (TextView) getView(R.id.et_industry);
        etCity = (TextView) getView(R.id.et_city);
        etIntro = (EditText) getView(R.id.et_intro);
        etContacts = (EditText) getView(R.id.et_contacts);
        etMobile = (EditText) getView(R.id.et_mobile);
        btnComplete = (Button) getView(R.id.btn_complete);
        wvContent = (WebView) getView(R.id.wv_content);

        etIndustry.setOnClickListener(this);
        etCity.setOnClickListener(this);
        btnComplete.setOnClickListener(this);

        initWebView();
        wvContent.loadUrl("http://m.cyb.3158.cn/cywlx");
    }

    /**
     * 初始化WebView
     */
    @SuppressLint("SetJavaScriptEnabled")
    private void initWebView() {
        /**
         * setAllowFileAccess 启用或禁止WebView访问文件数据 setBlockNetworkImage 是否显示网络图像
         * setBuiltInZoomControls 设置是否支持缩放 setCacheMode 设置缓冲的模式
         * setDefaultFontSize 设置默认的字体大小 setDefaultTextEncodingName 设置在解码时使用的默认编码
         * setFixedFontFamily 设置固定使用的字体 setJavaSciptEnabled 设置是否支持Javascript
         * setLayoutAlgorithm 设置布局方式 setLightTouchEnabled 设置用鼠标激活被选项
         * setSupportZoom 设置是否支持变焦
         * */
        WebSettings settings = wvContent.getSettings();
        settings.setJavaScriptEnabled(true);// 设置支持javascript脚本
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        // 1.NARROW_COLUMNS：可能的话使所有列的宽度不超过屏幕宽度；2.NORMAL：正常显示不做任何渲染；3.SINGLE_COLUMN：把所有内容放大webview等宽的一列中
        // settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        settings.setDisplayZoomControls(false);
        settings.setAllowFileAccess(true); // 启用或禁止WebView访问文件数据
        settings.setBuiltInZoomControls(false); //  隐藏缩放按钮
        settings.setSupportZoom(true); // 支持缩放
        // settings.setUseWideViewPort(true);// 可任意比例缩放
        settings.setLoadWithOverviewMode(true);//setUseWideViewPort方法设置webview推荐使用的窗口；设置webview加载的页面的模式
        settings.setGeolocationEnabled(true);// 启用地理定位
        settings.setDomStorageEnabled(true);
        settings.setSaveFormData(true);// 保存表单数据
        // settings.setSavePassword(true);
        // settings.setTextZoom(200);
        // settings.setMixedContentMode(1);
        // settings.setAcceptThirdPartyCookies();
        wvContent.setWebChromeClient(new WebChromeClient());
        wvContent.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                view.loadUrl(url);
                return false;
            }
        });
    }

    /**
     * 设置需展示的Html片段
     */
    private void setHtml(String protocol) {
        if (protocol != null) {
            wvContent.getSettings().setDefaultTextEncodingName("utf-8");
            wvContent.loadDataWithBaseURL(null, protocol, "text/html", "UTF-8", null);
        } else {
            ToastUtils.show(mActivity, "未获取到内容，请稍后重试");
        }
    }

    @Override
    public void onClick(View view) {
        if (!isCanClick(view)) return;
        switch (view.getId()) {
            case R.id.btn_complete:
                String industry = etIndustry.getText().toString();
                if (TextUtils.isEmpty(industry) || categoryId == 0) {
                    ToastUtils.show(mActivity, "请选择所处行业");
                    return;
                }
                String city = etCity.getText().toString();
                if (TextUtils.isEmpty(area)) {
                    ToastUtils.show(mActivity, "请选择所在城市");
                    return;
                }
                String intro = etIntro.getText().toString();
                if (TextUtils.isEmpty(intro)) {
                    ToastUtils.show(mActivity, "请简要说明您想要报导的内容");
                    return;
                }
                String contacts = etContacts.getText().toString();
                if (TextUtils.isEmpty(contacts)) {
                    ToastUtils.show(mActivity, "请输入联系人");
                    return;
                }
                String mobile = etMobile.getText().toString();
                if (TextUtils.isEmpty(mobile)) {
                    ToastUtils.show(mActivity, "请填写手机号码,示例:15012345678");
                    return;
                }
                if (mobile.length() != 11) {
                    ToastUtils.show(mActivity, "请填写手机号码,示例:15012345678");
                    return;
                }
                if (!RegexUtils.checkMobile(mobile)) {
                    ToastUtils.show(mActivity, "请填写手机号码,示例:15012345678");
                    return;
                }

                if (industry.equals(oldIndustry) && area.equals(oldCity) && intro.equals(oldIntro) && contacts.equals(oldContacts) && mobile.equals(oldMobile)) {
                    ToastUtils.show(mActivity, "该信息内容您已经提交啦");
                } else {
                    oldIndustry = industry;
                    oldCity = area;
                    oldIntro = intro;
                    oldContacts = contacts;
                    oldMobile = mobile;
                }

                HttpUtils.enrollAdd(categoryId, city, intro, contacts, mobile, new HttpCallback() {
                    @Override
                    public void onStart() {
                        super.onStart();
                        showProgress();
                    }

                    @Override
                    public void onSuccess(Object o) {
                        ToastUtils.show(mActivity, "请保存电话畅通,我们将尽快联系您");
                        etIndustry.setText(null);
                        etCity.setText(null);
                        etIntro.setText(null);
                        etContacts.setText(null);
                        etMobile.setText(null);
                        categoryId = 0;
                        area = null;
                    }

                    @Override
                    public void onError(String strMsg) {
                        super.onError(strMsg);
                        ToastUtils.show(mActivity, strMsg);
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                        hideProgress();
                    }
                });
                break;
            case R.id.et_industry:
                WheelViewDialog dialogFragment = WheelViewDialog.newInstance(5, categoryId);
                dialogFragment.show(getMyFragmentManager(), "Industry");
                dialogFragment.setSelectedCompleteListener(new com.sywb.chuangyebao.view.dialog.WheelViewDialog.SelectedCompleteListener() {
                    @Override
                    public void completeSelect(int[] i, String[] params) {
                        categoryId = i[0];
                        etIndustry.setText(params[0]);
                    }
                });
                break;
            case R.id.et_city:
                WheelViewDialog cityFragment = WheelViewDialog.newInstance(3, area);
                cityFragment.show(getMyFragmentManager(), "Area");
                cityFragment.setSelectedCompleteListener(new com.sywb.chuangyebao.view.dialog.WheelViewDialog.SelectedCompleteListener() {
                    @Override
                    public void completeSelect(int[] i, String[] params) {
                        area = params[0];
                        DistrictInfo areaInfo = DbManager.getInstance().queryById(area, DistrictInfo.class);
                        if (areaInfo != null) {
                            StringBuilder area = new StringBuilder();
                            if (!areaInfo.parentId.equals("0")) {
                                DistrictInfo provinceInfo = DbManager.getInstance().queryById(areaInfo.parentId, DistrictInfo.class);
                                if (provinceInfo != null) {
                                    area.append(provinceInfo.name).append(Constants.SPACE);
                                }
                            }
                            area.append(areaInfo.name);
                            etCity.setText(area.toString());
                        }
                    }
                });
                break;
        }
    }
}


